<?php
class DuansController extends AppController {

	var $name = 'Duans';
	var $helpers = array('Html','Ajax','Javascript','Paginator');
	var $components = array('RequestHandler');
	var $paginate = array(
		'limit' => 10,
		'order' => array(
			'Duan.vitrixh' => 'asc'
		)
    );
	function index() {
		$this->Duan->recursive = 0;
		$this->set('duans', $this->paginate());
	}
	function admin_index() {
		$this->layout = 'admin';
		$this->Duan->recursive = 0;
		$this->set('duans', $this->paginate());
	}
	/**
	 * view all duan vip
	 */
	function changetv($str){
		$marTViet=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
		"ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề"
		,"ế","ệ","ể","ễ",
		"ì","í","ị","ỉ","ĩ",
		"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
		,"ờ","ớ","ợ","ở","ỡ",
		"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
		"ỳ","ý","ỵ","ỷ","ỹ",
		"đ",
		"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
		,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
		"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
		"Ì","Í","Ị","Ỉ","Ĩ",
		"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
		,"Ờ","Ớ","Ợ","Ở","Ỡ",
		"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
		"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
		"Đ");

		$marKoDau=array("a","a","a","a","a","a","a","a","a","a","a"
		,"a","a","a","a","a","a",
		"e","e","e","e","e","e","e","e","e","e","e",
		"i","i","i","i","i",
		"o","o","o","o","o","o","o","o","o","o","o","o"
		,"o","o","o","o","o",
		"u","u","u","u","u","u","u","u","u","u","u",
		"y","y","y","y","y",
		"d",
		"A","A","A","A","A","A","A","A","A","A","A","A"
		,"A","A","A","A","A",
		"E","E","E","E","E","E","E","E","E","E","E",
		"I","I","I","I","I",
		"O","O","O","O","O","O","O","O","O","O","O","O"
		,"O","O","O","O","O",
		"U","U","U","U","U","U","U","U","U","U","U",
		"Y","Y","Y","Y","Y",
		"D");
		return str_replace($marTViet,$marKoDau,$str);
	}
	
	function autocomplete() {
     if ($this->RequestHandler->isAjax()) {
		$key_search = $this->changetv($_GET['q']);
		$key_search = strtolower($key_search);
		Configure::write('debug', 0);
		$this->autoLayout = false;
		$this->autoRender = false; 
		$this->Duan->recursive = -1;
		$results = $this->Duan->find('all', array('fields' => array('id', 'tieude', 'searchable'), 'conditions' => array('searchable LIKE "%'.$key_search.'%"')));
		$response = array();
		$i = 0;
		foreach($results as $result){
			$response[$i]['label'] = $result['Duan']['tieude'];
			$response[$i]['value'] = $result['Duan']['tieude'];
			$response[$i]['id'] = $result['Duan']['id'];
			$i++;
		}
		echo json_encode($response);
		//echo $response;
		} 
	} 
	
	function vipprojects(){
		$data = $this->paginate('Duan', array('Duan.phanloai' => '1'));
		if (isset($this->params['requested'])) {
			return $data;
        }
		$this->set('data', $data);
	}
	function normalprojects(){
		$data = $this->paginate('Duan', array('Duan.phanloai' => '0'));
		if (isset($this->params['requested'])) {
			return $data;
        }
		$this->set('data', $data);
	}
    function view_all(){
        $catalogues = $this->Duan->find('all');
        //check requesAction
        if(isset($this->params['requested'])){
            return $catalogues;
        }
        
    }
	function view($id = null) {
		$this->layout = 'duanview';
		if (!$id) {
			$this->Session->setFlash(__('Invalid duan', true));
			$this->redirect(array('action' => 'index'));
		}
		$tinraos = $this->Duan->Tinrao->find('all',array('conditions' => array('Tinrao.duan_id' => $id), 'order' => array('Tinrao.vitrixh ASC')));
		//print_r($tinraos);
		$this->set('tinraos', $tinraos);
		$this->set('duan', $this->Duan->read(null, $id));
	}
	function qtippro(){
		Configure::write('debug', 0);
		$this->autoLayout = false;
		$this->autoRender = false; 
		$idpro = $_GET['idpro'];
		$duan = $this->Duan->find('first', array('conditions' => array('id' => $idpro)));
		$response = array();
		$response['id'] = $duan['Duan']['id'];
		$response['tieude'] = $duan['Duan']['tieude'];
		$response['noidung'] = $duan['Duan']['noidung'];
		$response['hinhdaidien'] = $duan['Duan']['hinhdaidien'];
		$response['ngaydang'] = $duan['Duan']['ngaydang'];
		$response['diachi'] = $duan['Duan']['diachi'];
		echo json_encode($response);
		
	}
	function viewmorenormal($start = 0, $number_of_posts = 10) {
		/* connect to the db */
		//$start = 0;
		Configure::write('debug', 0);
		$this->autoLayout = false;
		$this->autoRender = false; 
		if(isset($_GET['start'])){
			$start = $_GET['start'];
		}
		if(isset($_GET['desiredPosts'])){
			$number_of_posts = $_GET['desiredPosts'];
		}
		$this->Session->write('start',$start);
		$duans = array();
		/* get the posts */
		$query = "SELECT * FROM duans WHERE phanloai = 0 ORDER BY vitrixh ASC LIMIT $start,$number_of_posts";
		$result = mysql_query($query);
		//$duans = $this->Duan->find('all',array('conditions' => array('Tinrao.phanloai' => 0, 'ORDER BY' => 'vitrixh DESC', 'LIMIT' => $number_of_posts)));
		while($row = mysql_fetch_assoc($result)) {
			/* preg_match("/<p>(.*)<\/p>/",$row['noidung'],$matches);
			$row['noidung'] = strip_tags($matches[0]); */
			$duans[] = $row;
		}
		/* return the posts in the JSON format */
		echo json_encode($duans);
	}
	function search() {
		$this->layout = 'duanview';
		$id = $_POST["idduan"];
		if (!$id) {
			$this->Session->setFlash(__('Invalid duan', true));
			$this->redirect(array('action' => 'index'));
		}
		$tinraos = $this->Duan->Tinrao->find('all',array('conditions' => array('Tinrao.duan_id' => $id)));
		//print_r($tinraos);
		$this->set('tinraos', $tinraos);
		$this->set('duan', $this->Duan->read(null, $id));
	}

	function add() {
		$this->layout = 'admin';
		if (!empty($this->data)) {
			$this->Duan->create();
			$this->data['Duan']['searchable'] = $this->changetv($this->data['Duan']['tieude']);
			if($this->data['Duan']['vitrixh']>=1&&$this->data['Duan']['vitrixh']<=10){
				for($i=10;$i>=$this->data['Duan']['vitrixh'];$i--){
					$query = 'UPDATE duans SET vitrixh='.($i+1).' WHERE vitrixh='.$i;
					$this->Duan->query($query);
				}
			}
			if ($this->Duan->save($this->data)) {
				$this->Session->setFlash(__('The duan has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The duan could not be saved. Please, try again.', true));
			}
		}
	}
	function change_vitrixh(){
		$idduan = $_POST['idduan'];
		$vitriedit = $_POST['vitrixh'];
		$vitri = $_POST['vitrixh'];
		
		for($i=10;$i>=$vitri;$i--){
			$query = 'UPDATE duans SET vitrixh='.($i+1).' WHERE vitrixh='.$i;
			$this->Duan->query($query);
		} 
		
		if($vitriedit){
			$query = 'UPDATE duans SET vitrixh='.$vitriedit.' WHERE id='.$idduan;
			$this->Duan->query($query);
			/* while($vitri<=10){
				$query = 'UPDATE duans SET vitrixh='. ($vitri+1) .' WHERE vitrixh='.$vitri;
				 if($this->Duan->query($query)){
					$vitri++;
				}else{
					break;
				} 
				 for($i=10;$i>=$vitri;$i--){
					$query = 'UPDATE duans SET vitrixh='.($i+1).' WHERE vitrixh='.$i;
					$this->Duan->query($query);
				} 
			} */
		}
		$this->redirect(array('action' => 'admin_index'));
		
	}
	function phanloai(){
		$this->layout = 'admin';
		$idduan = $_POST['idduan'];
		$loai = $_POST['phanloai'];
		$query = 'UPDATE duans SET phanloai = '.$loai.' WHERE id = '.$idduan;
		$this->Duan->query($query);
		$this->redirect(array('action' => 'admin_index'));
	}
	function admin_add() {
		$this->layout = 'admin';
		$this->data['Duan']['tieude'] = $_POST['tieude'];
		$this->data['Duan']['noidung'] = $_POST['noidung'];
		$this->data['Duan']['diachi'] = $_POST['diachi'];
		$this->data['Duan']['vitrixh'] = $_POST['vitrixh'];
		$this->data['Duan']['phanloai'] = $_POST['phanloai'];
		$this->data['Duan']['loban'] = $_POST['loban'];
		$this->data['Duan']['ngaydang'] = date('Y-m-d');
		$this->data['Duan']['searchable'] = $this->changetv($this->data['Duan']['tieude']);
		$target = $_SERVER['DOCUMENT_ROOT'].$this->webroot."app/webroot/upload/"; 
		$target = $target . basename( $_FILES['hinhdaidien']['name']) ; 
		$ok=1; 
		if(isset($_FILES['hinhdaidien'])){
		/* if ((($_FILES["hinhdaidien"]["type"] == "image/gif")
		|| ($_FILES["hinhdaidien"]["type"] == "image/jpeg")
		|| ($_FILES["hinhdaidien"]["type"] == "image/pjpeg"))
		&& ($_FILES["hinhdaidien"]["size"] < 20000)){ */
			if(move_uploaded_file($_FILES['hinhdaidien']['tmp_name'], $target)) 
			{
				echo "The file ". basename( $_FILES['hinhdaidien']['name']). " has been uploaded";
				//if (!empty($this->data) &&
				 //is_uploaded_file($this->data['Library']['File']['tmp_name'])) {
				

				
				$this->data['Duan']['hinhdaidien'] = $_FILES['hinhdaidien']['name'];
				
				

				//$this->redirect('somecontroller/someaction');
			//}
			
			}
		}
		/* if($this->data['Duan']['vitrixh']>=1&&$this->data['Duan']['vitrixh']<=10){
			for($i=10;$i>=$this->data['Duan']['vitrixh'];$i--){
				$query = 'UPDATE duans SET vitrixh='.($i+1).' WHERE vitrixh='.$i;
				$this->Duan->query($query);
			}
		} */
		if($this->data['Duan']['phanloai'] == 0){
			$i = $this->data['Duan']['vitrixh'];
			while(1){
				$duan = $this->Duan->find('first', array('conditions' => array('Duan.vitrixh' => $i, 'Duan.phanloai' => 0)));
				if($duan){
					$i++;
				}else{
					break;
				}
			}
			$query = 'UPDATE duans SET vitrixh='.$i.' WHERE vitrixh = '.$this->data['Duan']['vitrixh'];
			$this->Duan->query($query);	
		}
		if ($this->Duan->save($this->data)) {
			$this->Session->setFlash(__('Dự án được tạo thành công', true));
			$this->redirect(array('action' => 'admin_index'));
		} else {
			$this->Session->setFlash(__('Dự án chưa được tạo', true));
		}
		/* }
		else
		{
			echo "Invalid file";
		} */
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid duan', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Duan->save($this->data)) {
				$this->Session->setFlash(__('The duan has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The duan could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Duan->read(null, $id);
			
		}
	}
	function admin_edit($id = null) {
		$this->layout = "admin";
		if(!isset($_POST['tieude'])&&!isset($_POST['noidung'])
			&&!isset($_POST['diachi'])&&!isset($_POST['vitrixh'])
			&&!isset($_POST['phanloai'])&&!isset($_POST['loban'])){
			//$this->data = $this->Duan->read(null, $id);
				$this->set('duan', $this->Duan->read(null, $id));
			}
		else{
			$id = $_POST['id'];
			$tieude = $_POST['tieude'];
			$noidung = $_POST['noidung'];
			$diachi = $_POST['diachi'];
			$vitrixh = $_POST['vitrixh'];
			$phanloai = $_POST['phanloai'];
			$loban = $_POST['loban'];
			$ngaydang = date('Y-m-d');
			$searchable = $this->changetv($tieude);
			$hinhdaidien = $_POST['hinhdd'];
			$target = $_SERVER['DOCUMENT_ROOT'].$this->webroot."app/webroot/upload/"; 
			$target = $target . basename( $_FILES['hinhdaidien']['name']) ; 
			$ok=1; 
			if(isset($_FILES['hinhdaidien']['name'])){
			/* if ((($_FILES["hinhdaidien"]["type"] == "image/gif")
			|| ($_FILES["hinhdaidien"]["type"] == "image/jpeg")
			|| ($_FILES["hinhdaidien"]["type"] == "image/pjpeg"))
			&& ($_FILES["hinhdaidien"]["size"] < 20000)){ */
				if(move_uploaded_file($_FILES['hinhdaidien']['tmp_name'], $target)) 
				{
					echo "The file ". basename( $_FILES['hinhdaidien']['name']). " has been uploaded";
					//if (!empty($this->data) &&
					 //is_uploaded_file($this->data['Library']['File']['tmp_name'])) {
					

					
					$hinhdaidien = $_FILES['hinhdaidien']['name'];
					
					

					//$this->redirect('somecontroller/someaction');
				//}
				
				}
			}
			if($phanloai == 0){
				$i = $vitrixh;
				while(1){
					$duan = $this->Duan->find('first', array('conditions' => array('Duan.vitrixh' => $i, 'Duan.phanloai' => 0)));
					if($duan){
						$i++;
					}else{
						break;
					}
				}
				$query = 'UPDATE duans SET vitrixh='.$i.' WHERE vitrixh = '.$vitrixh;
				$this->Duan->query($query);	
			}
			$query = 'UPDATE duans SET tieude = "'.$tieude.'", noidung = "'.$noidung.'", diachi = "'.$diachi.'", hinhdaidien = "'.$hinhdaidien.'", vitrixh = '.$vitrixh.', phanloai = '.$phanloai.', loban = "'.$loban.'", searchable = "'.$searchable.'", ngaydang = "'.$ngaydang.'" WHERE id='.$id;
			if ($this->Duan->query($query)) {
				$this->Session->setFlash(__('Dự án đã được cập nhật', true));
				$this->redirect(array('action' => 'admin_index'));
			} else {
				$this->Session->setFlash(__('Dự án chưa được cập nhật', true));
			}
		}
		
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Không thể xóa được', true));
			$this->redirect(array('action'=>'admin_index'));
		}else{
			$da = $this->Duan->find('first', array('conditions' => array('Duan.id' => $id)));
			$i = $da['Duan']['vitrixh'] + 1;
			if ($this->Duan->delete($id)) {
				while(1){
					$duan = $this->Duan->find('first', array('conditions' => array('Duan.vitrixh' => $i)));
					if($duan && $duan['Duan']['phanloai'] == 0){
						$query = 'UPDATE duans SET vitrixh = '.($i-1).' WHERE vitrixh = '.$i;
						$this->Duan->query($query);
						$i++;
					}else{
						break;
					}
					
				}
				$this->Session->setFlash(__('Xóa thành công', true));
				$this->redirect(array('action'=>'admin_index'));
			}
			$this->Session->setFlash(__('Không thể xóa được', true));
			$this->redirect(array('action' => 'admin_index'));
		}
	}
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for duan', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Duan->delete($id)) {
			$this->Session->setFlash(__('Duan deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Duan was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	 
}
?>